package com.ys.peony.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.yklab.library.refreshlayout.listener.OnTouchListenerLoadAction;
import com.ys.peony.R;
import com.ys.peony.app.HttpURL;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.contract.BasicActivity;
import com.ys.peony.base.contract.CarPledgeContract;
import com.ys.peony.car300.CarDataManager;
import com.ys.peony.car300.CarSelectDialog;
import com.ys.peony.car300.CarUpdateActivity;
import com.ys.peony.car300.ItemModel;
import com.ys.peony.car300.ui.CarSeeActivity;
import com.ys.peony.enums.BusinessDetailStatus;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.model.CarModel;
import com.ys.peony.model.JiekuanrenModel;
import com.ys.peony.model.JiekuanrenResp;
import com.ys.peony.model.UserModel;
import com.ys.peony.presenter.CarPledgePresenter;
import com.ys.peony.ui.widget.CommonSearchView;
import com.ys.peony.ui.widget.Divider;
import com.ys.peony.utils.JSONUtil;
import com.ys.peony.utils.LoadingProgressUtils;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.StringUtils;
import com.ys.peony.utils.ToastUtils;
import com.ys.peony.utils.YsUtil;
import com.ys.peony.view.inter.YsDailogClickListener;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import com.yklab.library.refreshlayout.adapters.CommonRecyclerViewAdapter;
import com.yklab.library.refreshlayout.holder.CommonRecyclerViewHolder;
import com.yklab.library.refreshlayout.inter.OnClickCommonListener;



/**
 * 描述：車輛抵押頁面
 */
public class CarPledgeActivity extends BasicActivity<CarPledgeContract.iCarPledgeView, CarPledgePresenter> implements
        CarPledgeContract.iCarPledgeView, SwipeRefreshLayout.OnRefreshListener, YsDailogClickListener, OnClickCommonListener, CommonSearchView.ViewItemListener {

    private final static String TYPE_LOAN0 = "0"; //业务状态：新增
    private final static String TYPE_LOAN5 = "5"; //业务状态：面审打回
    private final static String TYPE_LOAN7 = "7"; //业务状态：资审打回

    public final static int TYPE_OPERATE_UPDATE = 1;//更新操作
    public final static int TYPE_OPERATE_SEE = 2;//查看操作

    private int mOperate = YSConstant.INVALID;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.search_layout)
    CommonSearchView mCommonSearchView;
    @BindView(R.id.view_blank)
    LinearLayout view_blank;

    private SearchView mSearchView;
    private SearchView.SearchAutoComplete mSearchAutoComplete;

    private CommonRecyclerViewAdapter mAdapter;
    private List<JiekuanrenModel> mList;
    private LinearLayoutManager mLayoutManager;

    private boolean isLoadAction = false;
    private boolean isLoading = false;
    private int lastVisiableItem = 1;

    //动作类型
    private int actionType = YSConstant.INVALID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_car_pledge;
    }

    @Override
    protected CarPledgePresenter initPresenter() {
        return new CarPledgePresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        mCommonSearchView.setListener(this, CommonSearchView.CARPLEDGE_TYPE);
        initMenu();
        initData();
        setListener();
        setAdapter();
        onRefresh();
    }

    /**
     * 描述：初始化menu
     */
    private void initMenu() {
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSearchAutoComplete.isShown()) {
                    try {
                        mSearchAutoComplete.setText("");
                        Method method = mSearchView.getClass().getDeclaredMethod("onCloseClicked");
                        method.setAccessible(true);
                        method.invoke(mSearchView);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    finish();
                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private void initData() {
        mList = new ArrayList<>();
        mLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
        mAdapter = new CommonRecyclerViewAdapter<JiekuanrenModel>(this, mList, R.layout.view_cartpledge_item) {
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {
                super.onBindViewHolder(holder, position);
                if (!isFooterView(position)) {
                    CarModel carModel = null;
                    JiekuanrenModel model = mList.get(position);
                    if (model == null) {
                        return;
                    }
                    if (model.getVehicleList().size() > 0) {
                        carModel = model.getVehicleList().get(model.getVehicleList().size() - 1);
                    }
                    ((CommonRecyclerViewHolder) holder)
                            .setText(R.id.tv_name, StringUtils.isEmpty(model.getClientName()) ? "" : model.getClientName())
                            .setText(R.id.tv_customerType, model.getClientClassfyName())
                            .setText(R.id.tv_businessType, BusinessDetailStatus.getStatus(model.getLoanStatus()))
                            .setText(R.id.tv_businessNum, model.getSerialNumber());
                    if (null != carModel) {
                        ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carNum, StringUtils.isEmpty(carModel.getPlate_number()) ? "" : carModel.getPlate_number());
                        ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carBrand, StringUtils.isEmpty(carModel.getBrand_name()) ? "" : carModel.getBrand_name());
                    } else {
                        ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carNum, "");
                        ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carBrand, "");
                    }
                    ((CommonRecyclerViewHolder) holder).setViewListener(R.id.basicinfo_rl);
                    ((CommonRecyclerViewHolder) holder).setViewListener(R.id.diyawu_rl);
                    ((CommonRecyclerViewHolder) holder).setViewListener(R.id.item);
                }
            }
        };
        mAdapter.isHasFooter(true);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE &&
                        lastVisiableItem + 1 >= mAdapter.getItemCount()) {
                    if (!isLoading && isLoadAction) {
                        changeLoading(true);
                        currentPage++;
                        actionType = YSConstant.ACTION_TYPE_UP;
                        getData();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisiableItem = mLayoutManager.findLastVisibleItemPosition();
            }
        });

    }

    private void setAdapter() {
        mRecyclerView.addItemDecoration(new Divider(this));
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void setListener() {
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.textGreen));
        //上拉行为监听
        mRecyclerView.setOnTouchListener(new OnTouchListenerLoadAction() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                isLoadAction = super.onTouch(view, motionEvent);
                return false;
            }
        });
        mAdapter.setOnClickListener(this);
    }

    private void getData() {
        if (!YsUtil.isValidNetWordAndUser()) {
            return;
        }
        UserModel userModel = SharePreferencesUtils.getInstance().getUserModel();
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", Long.parseLong(userModel.getId()));
        params.put("currentPage", currentPage);
        params.put("pageNum", pageNum);
        httpManagerUtils.get(HttpURL.busiLoanPage, params, new BaseRespCallBack() {
            @Override
            public void onRespSuccess(String respStr) {
                final JiekuanrenResp jiekuanrenResp = JSONUtil.parseObject(respStr, JiekuanrenResp.class);
                setData(jiekuanrenResp);
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                dismissFresh();
                changeLoading(false);
                showBlankView();
            }
        });
    }

    @Override
    public void onRefresh() {
        currentPage = 0;
        actionType = YSConstant.ACTION_TYPE_DOWN;
        getData();
    }

    private void dismissFresh() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    private void changeLoading(boolean loading) {
        if (mAdapter != null) {
            isLoading = loading;
            mAdapter.setLoadingStatus(loading);
        }

    }

    private void setData(final JiekuanrenResp jiekuanrenResp) {
        switch (actionType) {
            case YSConstant.ACTION_TYPE_UP://上拉
                changeLoading(false);
                if (jiekuanrenResp != null && jiekuanrenResp.getDataList() != null) {
                    final int size = mList.size();
                    mList.addAll((jiekuanrenResp.getDataList()));
                    mAdapter.notifyItemRangeInserted(size, mList.size());
                }
                break;
            case YSConstant.ACTION_TYPE_DOWN://下拉刷新
                dismissFresh();
                if (jiekuanrenResp != null && jiekuanrenResp.getDataList() != null) {
                    if (jiekuanrenResp.getDataList().size() < 1) {
                        showBlankView();
                    } else {
                        hideBlankView();
                    }
                    mList.clear();
                    mList.addAll(jiekuanrenResp.getDataList());
                    mAdapter.notifyDataSetChanged();
                } else {
                    showBlankView();
                }
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mSwipeRefreshLayout.setRefreshing(true);
        onRefresh();
    }

    @Override
    public void onFail(String msg) {
        LoadingProgressUtils.closeDialog();
        ToastUtils.showToast(msg);
    }

    @Override
    public void onSuccess(int code) {
        LoadingProgressUtils.closeDialog();
        switch (code) {
            case CarPledgeContract.GET_CAR_DETAIL:
                int size = CarDataManager.getInstance().getCarDetailModel().getBusiMortgageVo().getMortgageList().size();
                if (size == 0) {
                    ToastUtils.showToast("请先添加车辆信息");
                } else if (size == 1) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("position", 0);
                    if (mOperate == TYPE_OPERATE_UPDATE) {
                        skipToTargetPage(CarUpdateActivity.class, bundle);
                    } else if (mOperate == TYPE_OPERATE_SEE) {
                        skipToTargetPage(CarSeeActivity.class, bundle);
                    }
                } else {
                    CarSelectDialog carSelectDialog = new CarSelectDialog(this, this);
                    carSelectDialog.show();
                }
                break;
        }
    }

    @Override
    public void clickDialogItemModel(int type, ItemModel itemModel) {
        if (type >= 0) {
            Bundle bundle = new Bundle();
            bundle.putInt("position", type);
            if (mOperate == TYPE_OPERATE_UPDATE) {
                skipToTargetPage(CarUpdateActivity.class, bundle);
            } else if (mOperate == TYPE_OPERATE_SEE) {
                skipToTargetPage(CarSeeActivity.class, bundle);
            }
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search_view, menu);
        MenuItem searchItem = menu.findItem(R.id.menu_search);

        //通过MenuItem得到SearchView
        mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        mSearchAutoComplete = (SearchView.SearchAutoComplete) mSearchView.findViewById(R.id.search_src_text);
        mSearchView.setQueryHint("搜索通过姓名或编号");

        //设置输入框提示文字样式
        /*mSearchAutoComplete.setHintTextColor(getResources().getColor(android.R.color.darker_gray));
        mSearchAutoComplete.setTextColor(getResources().getColor(android.R.color.background_light));*/
        mSearchAutoComplete.setTextSize(14);
        //设置触发查询的最少字符数（默认2个字符才会触发查询）
        mSearchAutoComplete.setThreshold(1);

        //设置搜索框有字时显示叉叉，无字时隐藏叉叉
        mSearchView.onActionViewExpanded();
        mSearchView.setIconified(true);

        //修改搜索框控件间的间隔（这样只是为了更加接近网易云音乐的搜索框）
        LinearLayout search_edit_frame = (LinearLayout) mSearchView.findViewById(R.id.search_edit_frame);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) search_edit_frame.getLayoutParams();
        params.leftMargin = 0;
        params.rightMargin = 0;
        search_edit_frame.setLayoutParams(params);

        //监听SearchView的内容
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                mCommonSearchView.searchData(s.toString().trim(), HttpURL.busiLoanPage);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                mCommonSearchView.observerSearchText(mList, s.toString().trim());
                return false;
            }
        });
        mSearchAutoComplete.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    if (mSwipeRefreshLayout.getVisibility() == View.VISIBLE) {
                        mSwipeRefreshLayout.setVisibility(View.GONE);
                    }
                    if (mCommonSearchView.getVisibility() == View.GONE) {
                        mCommonSearchView.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (mSwipeRefreshLayout.getVisibility() == View.GONE) {
                        mSwipeRefreshLayout.setVisibility(View.VISIBLE);
                    }
                    if (mCommonSearchView.getVisibility() == View.VISIBLE) {
                        mCommonSearchView.setVisibility(View.GONE);
                    }
                }
            }
        });

        return true;
    }

    @Override
    public void onItemClick(View view, Object object) {
        doClickEvent(view, object);

    }

    @Override
    public void onClickListener(View view, int position) {
        if (position < 0 || position >= mList.size()) {
            return;
        }
        doClickEvent(view, mList.get(position));

    }

    private void doClickEvent(View view, Object o) {
        JiekuanrenModel jiekuanrenModel = (JiekuanrenModel) o;
        switch (view.getId()) {
            case R.id.basicinfo_rl:
                CarDataManager.clear();
                if (jiekuanrenModel != null && !TextUtils.isEmpty(jiekuanrenModel.getId())) {
                    if (TYPE_LOAN0.equals(jiekuanrenModel.getLoanStatus()) || TYPE_LOAN5.equals(jiekuanrenModel.getLoanStatus()) ||
                            TYPE_LOAN7.equals(jiekuanrenModel.getLoanStatus())) {
                        Bundle bundle = new Bundle();
                        bundle.putString("loanId", jiekuanrenModel.getId());
                        CarDataManager.getInstance().setLoanName(jiekuanrenModel.getClientName());
                        skipToTargetPage(CarInfoActivity.class, bundle);
                    } else {
                        ToastUtils.showToast("该业务状态无法操作");
                    }
                }
                break;
            case R.id.diyawu_rl:
                //清理数据
                CarDataManager.clear();
                if (jiekuanrenModel != null && !TextUtils.isEmpty(jiekuanrenModel.getId())) {
                    if (TYPE_LOAN0.equals(jiekuanrenModel.getLoanStatus()) || TYPE_LOAN5.equals(jiekuanrenModel.getLoanStatus()) ||
                            TYPE_LOAN7.equals(jiekuanrenModel.getLoanStatus())) {
                        if (!TextUtils.isEmpty(jiekuanrenModel.getId())) {
                            LoadingProgressUtils.showProgressDialog(CarPledgeActivity.this);
                            CarDataManager.getInstance().setLoanId(jiekuanrenModel.getId());
                            mOperate = TYPE_OPERATE_UPDATE;
                            presenter.getCarInfoById(jiekuanrenModel.getId());
                        }
                    } else {
                        ToastUtils.showToast("该业务状态无法操作");
                    }
                }
                break;
            case R.id.item:
                CarDataManager.clear();
                if (jiekuanrenModel != null && !TextUtils.isEmpty(jiekuanrenModel.getId())) {
                    if (!TextUtils.isEmpty(jiekuanrenModel.getId())) {
                        LoadingProgressUtils.showProgressDialog(CarPledgeActivity.this);
                        CarDataManager.getInstance().setLoanId(jiekuanrenModel.getId());
                        mOperate = TYPE_OPERATE_SEE;
                        presenter.getCarInfoById(jiekuanrenModel.getId());
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCommonSearchView.setListener(null, YSConstant.INVALID);
    }

    private void showBlankView() {
        view_blank.setVisibility(View.VISIBLE);
        mSwipeRefreshLayout.setVisibility(View.GONE);
    }

    private void hideBlankView() {
        view_blank.setVisibility(View.GONE);
        mSwipeRefreshLayout.setVisibility(View.VISIBLE);
    }
}
